package com.learn.core.controller.manager;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.learn.common.annotation.Log;
import com.learn.common.annotation.UserLoginToken;
import com.learn.common.enums.BusinessType;
import com.learn.common.enums.OperatorType;
import com.learn.common.enums.ResultEnum;
import com.learn.common.utils.*;
import com.learn.common.utils.result.CommonResult;
import com.learn.core.domain.LExamineSort;
import com.learn.core.dto.LExamineSortDTO;
import com.learn.core.service.ILExamineSortService;
import com.learn.framework.web.controller.WebController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 *
 * @author zhaohongyu
 * @ClassName LExamineSortController
 * @date 2021.04.26 11:33
 * @describe 问卷调查分类
 */
@Api("问卷调查分类")
@RestController
@RequestMapping("/manager/examineSort")
public class LExamineSortController extends WebController<LExamineSort> {
    @Autowired
    private ILExamineSortService ilExamineSortService;

    //机构树
    @ApiOperation(value = "机构树")
    @UserLoginToken
    @PostMapping("/tree")
    public CommonResult<Object> tree(){
        try {
            QueryWrapper<LExamineSort> queryWrapper = new QueryWrapper<LExamineSort>();
            queryWrapper.eq("state","1");
            List<LExamineSort> lOrganizations = ilExamineSortService.queryLExamineSortAll(queryWrapper);
            if(lOrganizations.size()>0)
                return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS,lOrganizations);
        }catch (Exception e){
            e.printStackTrace();
            return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult) ResultUtil.error(ResultEnum.ERROR);
    }

    //获取问卷调查列表
    @ApiOperation(value = "获取问卷调查分类列表")
    @UserLoginToken
    @PostMapping("/list")
    public PageResult<LExamineSort> list(@RequestBody LExamineSortDTO lExamineSortDTO){
        try {
            if (lExamineSortDTO==null||lExamineSortDTO.getPage()==null||lExamineSortDTO.getRows()==null){
                return new PageResult<>(null, null, ResultEnum.ERROR);
            }
            PageHelper.startPage(lExamineSortDTO.getPage(),lExamineSortDTO.getRows());
            QueryWrapper<LExamineSort> queryWrapper = new QueryWrapper<LExamineSort>();
            if(StringUtils.isNotEmpty(lExamineSortDTO.getName()))
                queryWrapper.like("examine_sort_name",lExamineSortDTO.getName());
            if(StringUtils.isNotEmpty(lExamineSortDTO.getState()))
                queryWrapper.eq("state",lExamineSortDTO.getState());
            if(StringUtils.isNotEmpty(lExamineSortDTO.getParentNode()))
                queryWrapper.eq("parent_node",lExamineSortDTO.getParentNode());
            Page<LExamineSort> lExamineSorts = (Page<LExamineSort>) ilExamineSortService.list(queryWrapper);
            if (CollectionUtils.isEmpty(lExamineSorts)) {
                return new PageResult<>(null, null, ResultEnum.NOT_EEIST);
            }
            // 返回
            return new PageResult(lExamineSorts.getTotal(), lExamineSorts, ResultEnum.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new PageResult(null,null,ResultEnum.ERROR);
        }
    }

    //添加问卷调查分类
    @ApiOperation(value = "添加问卷调查分类")
    @PostMapping("/add")
    @UserLoginToken
    @Log(title = "添加问卷调查分类", businessType = BusinessType.INSERT, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> add(@RequestBody LExamineSort lExamineSort, HttpServletRequest request){
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        try {
            if(lExamineSort!=null) {
                if (StringUtils.isEmpty(lExamineSort.getExamineSortName())) {
                    return (CommonResult) ResultUtil.error(ResultEnum.NOT_EXAMINE_SORT_NAME);
                }
                if (StringUtils.isEmpty(lExamineSort.getState())) {
                    lExamineSort.setState("1");
                }
                if (StringUtils.isEmpty(lExamineSort.getParentNode())) {
                    lExamineSort.setParentNode(0);
                }
                lExamineSort.setCreateTime(new Date());
                lExamineSort.setCreateUser(userId);
                if (ilExamineSortService.save(lExamineSort)) {
                    return (CommonResult) ResultUtil.success(ResultEnum.SUCCESS);
                }
            }
        }catch (Exception e){
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return  (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }


    //删除问卷调查分类
    @ApiOperation(value = "删除问卷调查分类")
    @PostMapping("/del")
    @UserLoginToken
    @Log(title = "删除问卷调查分类", businessType = BusinessType.DELETE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> del(@RequestBody LExamineSort lExamineSort){
        try {
            if(lExamineSort!=null){
                if(lExamineSort.getExamineSortId()!=null){
                    List<Integer> ids = new ArrayList<>();
                    ids.add(lExamineSort.getExamineSortId());
                    if(nodeStr(ids)){
                        return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
                    }
                }
            }
        }catch (Exception e)
        {
            return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }

    private Boolean nodeStr (List<Integer> lists) throws Exception{
        List<Integer> ids = new ArrayList<>();
        QueryWrapper<LExamineSort> queryWrapper = new QueryWrapper<LExamineSort>();
        for (int i = 0; i <lists.size() ; i++) {
            int orgid = lists.get(i);

            queryWrapper.eq("parent_node",orgid);
            List<LExamineSort> lExamineSorts = ilExamineSortService.list(queryWrapper);
            for (int j = 0; j < lExamineSorts.size(); j++) {
                LExamineSort lExamineSort = lExamineSorts.get(j);
                ids.add(lExamineSort.getExamineSortId());
            }
        }
        if(ids.size() > 0){
            this.nodeStr(ids);
        }

        ids.addAll(lists);
        queryWrapper = new QueryWrapper<LExamineSort>();
        queryWrapper.in(true, "examine_sort_id", ids);
        ilExamineSortService.remove(queryWrapper);

        return Boolean.TRUE;
    }

    //更新问卷调查分类graduation
    @ApiOperation(value = "更新问卷调查分类")
    @PostMapping("/edit")
    @UserLoginToken
    @Log(title = "更新问卷调查分类", businessType = BusinessType.UPDATE, operatorType = OperatorType.SYSTEM)
    public CommonResult<Object> edit(@RequestBody LExamineSort lExamineSort, HttpServletRequest request) {
        String  token = request.getHeader("token");
        String userId = JwtUtil.getUserId(token);
        if(lExamineSort!=null){
            lExamineSort.setUpdateTime(new Date());
            lExamineSort.setUpdateUser(userId);
            if(ilExamineSortService.updateById(lExamineSort)){
                return (CommonResult)ResultUtil.success(ResultEnum.SUCCESS);
            }
        }
        return (CommonResult)ResultUtil.error(ResultEnum.ERROR);
    }
}
